package org.jvnc.rfb.proto.encoding;

/**
* <br><br><center><table border="1" width="80%"><hr>
* <p>
* Copyright (C) 2006-2007 by Deon Wu
* <p>
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.0
* of the License, or (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* <a href="http://www.gnu.org/licenses/old-licenses/gpl-2.0.html">GNU Lesser General Public License</a>
* for more details.
* <p>
* You should have received a copy of the <a href="http://www.gnu.org/licenses/old-licenses/gpl-2.0.html">
* GNU Lesser General Public License</a> along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* <hr></table></center>
* **/

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.io.DataInput;
import java.io.IOException;

import org.jvnc.rfb.proto.Colour;
import org.jvnc.rfb.proto.Rectangle;

public class RRE extends Encoding {
	private int subRect = 0;
	private Rectangle rect = null;
	private Color background = null;
	private SubRect[] subs = null;
	public RRE(Rectangle rect){
		this.rect = rect;
	}

	@Override
	public void fillEncoding(DataInput in) throws IOException {
		subRect = in.readInt();
		background = readColor(in);
		subs = new SubRect[subRect];
		for(int i = 0; i < subRect; i++){
			subs[i] = new SubRect();
			subs[i].fillSubRect(in);
		}
	}
	
	public Image deCode(Image frame){
		Graphics g = frame.getGraphics();
		g.setColor(background);
		g.fillRect(rect.getPositionX(), rect.getPositionY(), rect.getWidth(), rect.getHeight());
		for(SubRect sub : subs){
			g.setColor(sub.color);
			g.fillRect(rect.getPositionX() + sub.x, rect.getPositionY() + sub.y,
					sub.width, sub.height);
		}
		return null;
	}
	
	private class SubRect{
		public Color color = null;
		public int x;
		public int y;
		public int width;
		public int height;
		public void fillSubRect(DataInput in) throws IOException{
			color = readColor(in);
			x = in.readUnsignedShort();
			y = in.readUnsignedShort();
			width = in.readUnsignedShort();
			height = in.readUnsignedShort();
		}
	}
	
	private Color readColor(DataInput in) throws IOException{
		Color color = null;
		int bytesPixel = rect.getFormat().bitsPerPixel / 8;
		byte[] bg_buf = new byte[bytesPixel];
		in.readFully(bg_buf);
		if(bytesPixel == 1){
			genRGBColors();
			color = this.color265[bg_buf[0] & 0xff];
		}else{
			color = new Color(bg_buf[2] & 0xff,bg_buf[1] & 0xff,bg_buf[0] & 0xff);
		}
		return color;
	}
}
